package urlBase.impl;

import redis.clients.jedis.Jedis;
import urlBase.URLBase;

public class RedisBase implements URLBase {

    private RedisBase(){}
    private static RedisBase instance = new RedisBase();
    public static RedisBase getURLBase() {
        return instance;
    }


    @Override
    public synchronized void addIndex(String url) {
        Jedis con = new Jedis("192.168.1.21",6379);
        con.rpush("index",url);
        con.close();
    }

    @Override
    public synchronized void addItem(String url) {
        Jedis con = new Jedis("192.168.1.21",6379);
        con.rpush("item",url);
        con.close();
    }

    @Override
    public synchronized String getIndex() {
        Jedis con = new Jedis("192.168.1.21",6379);
        String url = con.lpop("index");
        con.close();
        return url;
    }

    @Override
    public synchronized String getItem() {
        Jedis con = new Jedis("192.168.1.21",6379);
        String url = con.lpop("item");
        con.close();
        return url;
    }

    public synchronized long size()
    {
        Jedis con = new Jedis("192.168.1.21",6379);
        long size = con.llen("item");
        con.close();
        return size;
    }

    public synchronized void discard(String url) {
        Jedis con = new Jedis("192.168.1.21",6379);
        long offset1 = BKDR(url);
        long offset2 = FNVHash1(url);
        con.setbit("BloomFilter", offset1, true);
        con.setbit("BloomFilter", offset2, true);
        con.close();
    }

    public boolean exist(String url) {
        Jedis con = new Jedis("192.168.1.21",6379);
        long offset1 = BKDR(url);
        long offset2 = FNVHash1(url);
        return con.getbit("BloomFilter",offset1) && con.getbit("BloomFilter",offset2);
    }


    //使用set方法的传统去重
//    public void discard(String url)
//    {
//        Jedis con = new Jedis("192.168.1.21",6379);
//        con.sadd("trash", url);
//        con.close();
//    }

//    public boolean exist(String url)
//    {
//        Jedis con = new Jedis("192.168.1.21",6379);
//        return con.sismember("trash",url);
//    }

    public int BKDR(String str) {
        int hash = 0;
        int seed = 131;
        for (int i = 0; i != str.length(); ++i) {
            hash = seed * hash + str.charAt(i);
        }
        if (hash < 0)
            hash += Integer.MAX_VALUE;
        return hash;
    }

    public int FNVHash1(String str)
    {
        final int p = 16777619;
        int hash = (int)2166136261L;
        for(int i=0;i<str.length();i++)
            hash = (hash ^ str.charAt(i)) * p;
        hash += hash << 13;
        hash ^= hash >> 7;
        hash += hash << 3;
        hash ^= hash >> 17;
        hash += hash << 5;

        if(hash<0)
            hash+=Integer.MAX_VALUE;
        return hash;
    }
}
